/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * CompanyController.java
 */
package com.yixun.qfbao.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yixun.common.controller.BaseController;
import com.yixun.common.exception.YIXUNExceptionCode;
import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.common.service.ApiServiceClient;
import com.yixun.qfbao.common.service.impl.ApiServiceClientImpl;
import com.yixun.qfbao.controller.vo.CompanyVo;
import com.yixun.qfbao.model.Area;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.Logo;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.LogoDto;
import com.yixun.qfbao.model.enums.AuthorizationServiceEnum;
import com.yixun.qfbao.model.enums.CheckStatusEnum;
import com.yixun.qfbao.model.enums.CompanyTypeEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.LogoTypeEnum;
import com.yixun.qfbao.service.AreaService;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.service.DictionaryService;
import com.yixun.qfbao.service.LogoService;

/**
 * [文件名称]<br>
 * CompanyController.java<br>
 * <br>
 * [文件描述]<br>
 * 商户 Controller<br>
 * <br>
 * [修改记录]<br>
 * 2015-12-10 14:36:24 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Controller
@RequestMapping("/jr/company")
public class CompanyController extends BaseController {
	@Autowired
	private CompanyService mservice;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private LogoService logoService;
	@Autowired
	private DepartmentDao departmentDao;
	
	@Value("#{configProperties['v10.api.url']}")
	private String apiUrl;
	
	private static Logger log = Logger.getLogger(CompanyController.class);
	
	@RequestMapping({"/manage"})
	public String index(Model model){
		return "/jr/company/manage";
	}
	@RequestMapping({"/channelManage"})
	public String index2(Model model){
		return "/jr/company/channel_manage";
	}
	
	@RequestMapping("/list")
	public @ResponseBody Page<Company> indexJson(CompanyVo entity,String op,HttpServletResponse response,int page,int rows){
		Page<Company> pageModel = null;
		try {
			if("channel".equals(op)){
				entity.setCompanyType(Long.parseLong("1"));
			}else{
				entity.setCompanyType(Long.parseLong("20"));
			}
			if(StringUtils.isNotBlank(entity.getOutsideSwitch()) && "-1".equals(entity.getOutsideSwitch())){
				entity.setOutsideSwitch(null);
			}
			entity.setOrders("t.create_time desc");
			pageModel = mservice.getPageModel(entity.toDto(),PageUtil.begin(page,rows),rows);
			List<Company> list =  pageModel.getRows();
			for(Company company:list){
				String authorizationArray = company.getAuthorization();
				if (!StringUtils.isEmpty(authorizationArray)){
					String authorizationNames = "";
					String array[] = authorizationArray.split(",");
					if (array.length>0){
						for(int i=0; i<array.length; i++){
							authorizationNames+=AuthorizationServiceEnum.getByNo(array[i]).getDes();
							
							if(i!=array.length-1)authorizationNames+=",";
						}
					}
					company.setAuthorizationName(authorizationNames);
				}
				
				//查询公司类型
				if(!StringUtils.isEmpty(String.valueOf(company.getCompanyType()))){
					Dictionary dictionary = dictionaryService.selectById(company.getCompanyType());
					if(dictionary!=null){
						company.setCompanyTypeName(dictionary.getDicName());
					}
				}
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Company>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Company>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}
	
	@RequestMapping("/view")
	public String formView(Model model,CompanyVo entity,String isView,HttpServletResponse response) throws IOException{
		//isView 0:查看模式  1新增或编辑模式
		model.addAttribute("isView", isView);
		try {
			if(null==entity.getId()){
				model.addAttribute("model",entity);
			}else{
				Company company=mservice.selectById(entity.getId());
				StringBuffer authorizationName=new StringBuffer("");
				String authorization=company.getAuthorization();
				if(StringUtils.isNotBlank(authorization)){
					String[] authorizationArray=authorization.split(",");
					for(int i=0;i<authorizationArray.length;i++){
						authorizationName.append(AuthorizationServiceEnum.getByNo(authorizationArray[i]).getDes());
						if(i!=(authorizationArray.length-1)){
							authorizationName.append(",");
						}
					}
				}
				//设置授权
				company.setAuthorizationName(authorizationName.toString());
				//设置公司类型
				company.setCompanyTypeName(dictionaryService.selectById(company.getCompanyType()).getDicName());
				//查询城市
				Area cityArea=areaService.selectById(company.getCity());
				company.setCityName(cityArea==null?"":cityArea.getName());
				
				Area provinceArea=areaService.selectById(company.getProvince());
				company.setProvinceName(provinceArea==null?"":provinceArea.getName());
				model.addAttribute("model",company);
				//查询logo
				LogoDto dto = new LogoDto();
				dto.setLogoMerchantid(company.getId());
				List<Logo> lists = logoService.selectListByDto(dto);
				for(Logo logo:lists){
					if(LogoTypeEnum.TYPE_1.getNo().equals(logo.getLogoType())){
						model.addAttribute("h5LoginLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_2.getNo().equals(logo.getLogoType())){
						model.addAttribute("assiantLoginLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_3.getNo().equals(logo.getLogoType())){
						model.addAttribute("assiantIndexLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_4.getNo().equals(logo.getLogoType())){
						model.addAttribute("assiantExitLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_5.getNo().equals(logo.getLogoType())){
						model.addAttribute("developersLoginLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_6.getNo().equals(logo.getLogoType())){
						model.addAttribute("developersIndexLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_7.getNo().equals(logo.getLogoType())){
						model.addAttribute("agencyLoginLogo",logo.getLogoUrl());
					}
					if(LogoTypeEnum.TYPE_8.getNo().equals(logo.getLogoType())){
						model.addAttribute("agencyIndexLogo",logo.getLogoUrl());
					}
				}
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败: {}",e);
		}catch (Exception e) {
			log.error("创建失败: {}",e);
		}
		return "/jr/company/save_edit";
	}
	
	@RequestMapping("/save_edit")
	public @ResponseBody Map<String,String> saveOrUpdate(Model model,CompanyVo entity,HttpServletResponse response) throws IOException{
		Map<String,String> res = new HashMap<String, String>();
		try {
			if(entity.getCompanyType()==null){
				entity.setCompanyType(Long.parseLong("20"));
			}
			Dictionary dictionary = dictionaryService.selectById(entity.getCompanyType());
			if(dictionary.getDicValue().equals(CompanyTypeEnum.COMPANY_TYPE_VALUE_0.getCode())){
				//添加中介公司，验证公司ID,公司名称
				if(StringUtils.isBlank(entity.getCompanyName())){
					res.put("isSuccess", "1");
					res.put("errorMsg","公司名称必填!");
					return res;
				}
			}else{
				//非中介公司
				if(StringUtils.isBlank(entity.getCompanyName())){
					res.put("isSuccess", "1");
					res.put("errorMsg","公司名称必填!");
					return res;
				}
				if(StringUtils.isBlank(entity.getDomain())){
					res.put("isSuccess", "1");
					res.put("errorMsg","域名必填!");
					return res;
				}else{ 
					if(entity.getId()==null){
						//判断域名是否存在
						CompanyDto dto = new CompanyDto();
						dto.setDomain(entity.getDomain());
						List<Company> list = mservice.selectListByDto(dto);
						if(list.size()>0){
							res.put("isSuccess", "1");
							res.put("errorMsg","域名已存在，请更换!");
							return res;
						}
					}else{
						Company oldCompany = mservice.selectById(entity.getId());
						if(!entity.getDomain().equals(oldCompany.getDomain())){
							//修改域名后进行判断域名是否和其它域名冲突
							CompanyDto dto = new CompanyDto();
							dto.setDomain(entity.getDomain());
							List<Company> list = mservice.selectListByDto(dto);
							if(list.size()>0){
								res.put("isSuccess", "1");
								res.put("errorMsg","域名已存在，请更换!");
								return res;
							}
						}
					}
				}
				/*if(StringUtils.isBlank(entity.getH5LoginLogo())){
					res.put("isSuccess", "1");
					res.put("errorMsg","分销商h5登录页logo必填!");
					return res;
				}
				if(StringUtils.isBlank(entity.getAssiantLoginLogo())){
					res.put("isSuccess", "1");
					res.put("errorMsg","案场助手登录页logo必填!");
					return res;
				}
				if(StringUtils.isBlank(entity.getAssiantIndexLogo())){
					res.put("isSuccess", "1");
					res.put("errorMsg","案场助手首页logo必填!");
					return res;
				}
				if(StringUtils.isBlank(entity.getAssiantExitLogo())){
					res.put("isSuccess", "1");
					res.put("errorMsg","案场助手退出页logo必填!");
					return res;
				}*/
				//重置公司名称
				entity.setCompanyName(entity.getCompanyName());
				//清空授权
				entity.setAuthorization("");
			}
			//清空外部系统关联号
			entity.setExternalNumber("");
			if(null==entity.getCity()){
				entity.setCity(null);
			}
			CompanyDto dto = new CompanyDto();
			ConvertUtils.register(new DateConverter(null), java.util.Date.class);
			BeanUtils.copyProperties(dto, entity);
			//新建机构时需要记录日志，326为auth的id
			entity.setOptUser(Long.parseLong("326"));
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			if(entity.getId()!=null){
				Company company = mservice.selectById(entity.getId());
				entity.setStatus(company.getStatus());
			}else{
				//新增
				entity.setStatus(CheckStatusEnum.SUCCESS.getNo());
			}
			int count=mservice.saveOrUpdate(entity);
			if(count>0){
				res.put("isSuccess", "0");
				res.put("errorMsg","保存成功");
			}else{
				res.put("isSuccess", "1");
				res.put("errorMsg","保存失败");
			}
		}catch (Exception e) {
			res.put("isSuccess", "1");
			res.put("errorMsg","保存失败: {}");
			log.error("编辑失败: {}",e);
		}
		return res;
	}
	
	@RequestMapping("/del")
	public @ResponseBody Map<String,Object> destroy(CompanyVo entity,HttpServletResponse response) throws IOException{
		Map<String,Object> res = new HashMap<String, Object>();
		try {
			//新建机构时需要记录日志，326为auth的id
			entity.setOptUser(Long.parseLong("326"));
			int destroyCount = mservice.destroy(entity.toDto());
			res.put("count",destroyCount);
			res.put("row",entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return res;
	}
	
	/**
	 * 获取商户列表
	 * @param entity
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/getList")
	public String companyList(CompanyVo entity,HttpServletResponse response) throws IOException{
		entity.setCompanyType(Long.parseLong("20"));
		List<Company> list = mservice.selectListByDto(entity.toDto());
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(JSONObject.toJSONString(list));
		return null;
	}
	
	
	@RequestMapping("/queryCompany")
	public void queryCompany(Integer page,Integer rows,String keyword ,HttpServletResponse response) throws IOException{
		Map<String, String> properties=new HashMap<String, String>();
		properties.put("companyCname", keyword==null?"":keyword);
		ApiServiceClient apiServiceClient=new ApiServiceClientImpl();
		try {
			String resposeStr=apiServiceClient.requestByGet(apiUrl, properties);
			JSONObject resultObj=JSONObject.parseObject(resposeStr);
			response.getWriter().write(resultObj.getJSONArray("companyAccount").toJSONString());
		} catch (Exception e) {
			log.error("获取公司失败: {}",e);
			response.getWriter().write(new JSONArray().toJSONString());
		}
		
	}
	
	@RequestMapping("/distributionList")
	public @ResponseBody Page<Company> distributionList(Long companyType,String companyIds,int page,int rows){
		Page<Company> pageModel = null;
		try {
			CompanyDto companyDto=new CompanyDto();
			companyDto.setCompanyType(companyType);
			if(StringUtils.isNotBlank(companyIds)){
				List<Long> list=new ArrayList<Long>();
				String[] arrayIds=companyIds.split(",");
				for(int i=0;i<arrayIds.length;i++){
					list.add(Long.valueOf(arrayIds[i]));
				}
				companyDto.setNotIds(list);
			}
			pageModel = mservice.getDistributionPage(companyDto,PageUtil.begin(page,rows),rows);
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Company>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<Company>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}

	/**
	 * 获取公司列表
	 * @param entity
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/getCompanyList")
	public String getCompanyList(CompanyVo entity,HttpServletResponse response) throws IOException{
		List<Company> list = mservice.selectListByDto(entity.toDto());
		/*response.setCharacterEncoding("UTF-8");*/
		response.getWriter().write(JSONObject.toJSONString(list));
		return null;
	}
	
}
